package org.redis.cluster.redis.processor;

import java.nio.ByteBuffer;

import org.apache.commons.lang3.ArrayUtils;
import org.redis.cluster.processor.RedisReplyProcessor;
import org.redis.cluster.redis.transport.RedisReply;

public abstract class AbstractRedisSingleReplyProcessor<T extends RedisReply> implements RedisReplyProcessor<T> {
	
	private final static int OTHER_BYTE_COUNT=3;

	@Override
	public byte[] process(T reply) {
		Object value=getValue(reply);
		if(value==null) {
			return ArrayUtils.EMPTY_BYTE_ARRAY;
		}
		
		byte valueByte[]=value.toString().getBytes();
		ByteBuffer byteBuffer=ByteBuffer.allocate(valueByte.length+OTHER_BYTE_COUNT);
		
		byteBuffer.put(getStartByte());
		byteBuffer.put(valueByte);
		byteBuffer.put(RedisReply.END_1);
		byteBuffer.put(RedisReply.END_2);
		
		return byteBuffer.array();
	}
	
	/**
	 * 返回值
	 * @param reply
	 * @return
	 */
	protected abstract Object getValue(T reply);
	
	/**
	 * 返回开始字节
	 * @return
	 */
	protected abstract byte getStartByte();
}